using DevExpress.Data.Filtering;
using DevExpress.Xpo;
using SmartPeople.Framework.SecuritySpace;

namespace SmartPeople.Framework.Security.Providers.XPO
{
    internal class XPSecuritySecuredTypeActions : ISecuritySecuredTypeActions
    {
        private XPSecuritySecuredType securedType;

        public XPSecuritySecuredTypeActions(XPSecuritySecuredType securedDocument)
        {
            securedType = securedDocument;
        }


        int ISecuritySecuredTypeActions.Count
        {
            get
            {
                int resultCount = securedType.actions.Count;
                if (securedType.BaseSecuredType != null)
                    resultCount += securedType.BaseSecuredType.Actions.Count;
                return resultCount;
            }
        }

        public ISecuritySecuredTypeAction this[string actionName]
        {
            get
            {
                CriteriaOperator criteria = new BinaryOperator("Name", actionName, BinaryOperatorType.Equal);
                XPCollection<XPSecuritySecuredTypeAction> actions = new
                    XPCollection<XPSecuritySecuredTypeAction>(securedType.actions, criteria);
                if (actions.Count == 1)
                {
                    return actions[0];
                }

                if (securedType.BaseSecuredType != null)
                {
                    return securedType.BaseSecuredType.Actions[actionName];
                }

                return null;
            }
        }

        #region CreateAction

        public ISecuritySecuredTypeAction CreateAction(string actionName)
        {
            XPSecuritySecuredTypeAction securedTypeAction = new XPSecuritySecuredTypeAction(securedType.Session);
            securedTypeAction.Name = actionName;
            securedTypeAction.securedType = securedType;
            securedType.actions.Add(securedTypeAction);
            //securedTypeAction.Save();
            return securedTypeAction;
        }

        #endregion
    }
}